package com.zh.common.base

import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ThreadUtils
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import com.zh.common.ktx.viewBinding
import com.zh.common.utils.ActManager
import com.zh.common.utils.JumpActivity
import com.zh.common.utils.LanguageUtil
import com.zh.common.view.dialog.LoadingDialog
import me.jessyan.autosize.AutoSizeCompat
import me.jessyan.autosize.AutoSizeConfig
import java.lang.reflect.ParameterizedType

/**
 * ......................我佛慈悲....................
 * ......................_oo0oo_.....................
 * .....................o8888888o....................
 * .....................88" . "88....................
 * .....................(| -_- |)....................
 * .....................0\  =  /0....................
 * ...................___/`---'\___..................
 * ..................' \\|     |// '.................
 * ................./ \\|||  :  |||// \..............
 * .............../ _||||| -卍-|||||- \..............
 * ..............|   | \\\  -  /// |   |.............
 * ..............| \_|  ''\---/''  |_/ |.............
 * ..............\  .-\__  '-'  ___/-. /.............
 * ............___'. .'  /--.--\  `. .'___...........
 * .........."" '<  `.___\_<|>_/___.' >' ""..........
 * ........| | :  `- \`.;`\ _ /`;.`/ - ` : | |.......
 * ........\  \ `_.   \_ __\ /__ _/   .-` /  /.......
 * ....=====`-.____`.___ \_____/___.-`___.-'=====....
 * ......................`=---='.....................
 * ..................佛祖开光 ,永无BUG................
 * @auth xiaohua
 * @time 2020/10/7 - 15:21
 * @desc Activity基类
 */
abstract class BaseActivity<VB : ViewBinding> : RxAppCompatActivity(), JumpActivity {

    var tag = ""
    val viewBinding by lazy { viewBinding<VB>() }
    private var loadingDialog: LoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        if (intent.hasExtra("tag")) {
            tag = intent.getStringExtra("tag") ?: ""
            ActManager.getInstance().add(this)
        }
        initImmersionBars()
        //初始化组件
        ARouter.getInstance().inject(this)
        initView(savedInstanceState)
    }

    open val interceptKeyBoard = true
    open val smartRefresh: SmartRefreshLayout? = null
    abstract fun initView(savedInstanceState: Bundle?)

    override fun onPause() {
        super.onPause()
        //页面消失的时候，软键盘自动关闭
        if (KeyboardUtils.isSoftInputVisible(this)) {
            KeyboardUtils.hideSoftInput(this)
        }
    }

    override fun finish() {
        if (!TextUtils.isEmpty(tag)) {
            ActManager.getInstance().removeTag(this)
        }
        super.finish()
    }

    /**
     * 点击EditText以外区域隐藏软键盘
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN && interceptKeyBoard) {
            val focusView = currentFocus
            if (focusView is EditText && isShouldHideKeyboard(focusView, ev)) {
                val isNotHide = notHideKeyboard()?.any {
                    !isShouldHideKeyboard(it, ev)
                } ?: false
                if (!isNotHide) KeyboardUtils.hideSoftInput(focusView)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    //不需要点击隐藏软键盘的view
    open fun notHideKeyboard(): Array<View>? {
        return null
    }

    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

    /**
     * 语言适配
     */
    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(newBase?.let { LanguageUtil().attachBaseContext(it) })
    }

    private fun getLoadingDialog() {
        loadingDialog ?: also { loadingDialog = LoadingDialog(this) }
    }

    /**
     * 显示加载dialog
     */
    fun showLoading() {
        try {
            getLoadingDialog();loadingDialog?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 结束dialog
     */
    fun dismissLoading() {
        try {
            loadingDialog?.let { if (it.isShowing) it.dismiss() }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 在任何情况下本来适配正常的布局突然出现适配失效，适配异常等问题，只要重写 Activity 的 getResources() 方法即可
     * 如果是 Dialog、PopupWindow 等控件出现适配失效或适配异常，同样在每次 show() 之前调用 AutoSize#autoConvertDensity() 即可
     */
    override fun getResources(): Resources {
        if (ThreadUtils.isMainThread()) {
            val isBaseWidth =
                AutoSizeConfig.getInstance().screenWidth < AutoSizeConfig.getInstance().screenHeight
            AutoSizeCompat.autoConvertDensity(super.getResources(), 375f, isBaseWidth)
        }
        return super.getResources()
    }

    //结束刷新
    private fun finishSmartRefresh() {
        smartRefresh?.let { if (it.isRefreshing) it.finishRefresh(); if (it.isLoading) it.finishLoadMore() }
    }
}